package service

import (
	"gin-worked/app/system/model"
	"strconv"
	"time"
)

type SystemRoleListApi struct {
	List  interface{}
	Total int
}

func SystemRoleList(roleId string, limit string, offset string) Res {

	roleIds, _ := strconv.Atoi(roleId)
	data := &model.SystemRole{RoleId: roleIds}
	field := []string{"id", "system_id", "role_id", "status"} //查询字段
	offsets, _ := strconv.Atoi(offset)
	limits, _ := strconv.Atoi(limit)
	list, err := model.SystemRoleList(data, field, "create_time ASC", offsets, limits)

	if err != nil {
		return Res{0, err.Error(), ""}
	}

	total := model.SystemRoleTotal(data)
	return Res{1, "success", SystemRoleListApi{List: list, Total: int(total)}}

}

// SystemRoleAdd 管理员关联角色
func SystemRoleAdd(system_id string, role_id string) Res {

	roleId, _ := strconv.Atoi(role_id)
	systemId, _ := strconv.Atoi(system_id)
	times := time.Now().Unix()

	where := &model.SystemRole{
		//RoleId:     roleId,
		SystemId:   systemId,
		DeleteTime: strconv.Itoa(0),
		Status:     strconv.Itoa(1),
	}
	field := []string{"id"} //查询字段
	//验证角色是否已经添加
	info, _ := model.SystemRoleInfo(where, field)
	if info.Id > 0 {
		return Res{0, "该角色以关联", ""}
	}

	//关联角色
	data := &model.SystemRole{
		RoleId:     roleId,
		SystemId:   systemId,
		Status:     strconv.Itoa(1),
		DeleteTime: strconv.Itoa(0),
		CreateTime: strconv.FormatInt(times, 10),
		UpdateTime: strconv.FormatInt(times, 10),
	}

	id, err := model.SystemRoleAdd(data)

	if err != nil {
		return Res{0, err.Error(), ""}
	}

	return Res{1, "success", id}
}

// SystemRoleEdit 管理员修改角色
func SystemRoleEdit(id string, system_id string, role_id string) Res {

	ids, _ := strconv.Atoi(id)
	roleId, _ := strconv.Atoi(role_id)
	systemId, _ := strconv.Atoi(system_id)
	//times := time.Now().Unix()

	where := &model.SystemRole{
		//RoleId:     roleId,
		SystemId:   systemId,
		DeleteTime: strconv.Itoa(0),
		Status:     strconv.Itoa(1),
	}

	field := []string{"id"} //查询字段
	info, _ := model.SystemRoleInfo(where, field)
	if info.Id > 0 {
		return Res{0, "该角色以关联", ""}
	}

	data := &model.SystemRole{
		Id: ids,
	}
	content := map[string]interface{}{"role_id": roleId}

	err := model.SystemRoleEdit(data, content)

	if err != nil {
		return Res{0, err.Error(), ""}
	}
	return Res{1, "success", ""}
}

// SystemRoleDel 删除管理员关联角色
func SystemRoleDel(id string) Res {
	ids, _ := strconv.Atoi(id)
	where := &model.SystemRole{
		Id: ids,
	}

	err := model.SystemRoleDel(where)

	if err != nil {
		return Res{0, err.Error(), ""}
	}
	return Res{1, "success", ""}
}
